const Order = require('../models/Order');
const OrderItem = require('../models/OrderItem');
const Product = require('../models/Product');
const User = require('../models/User');

// 创建订单
exports.create = async (req, res) => {
  try {
    const { items, address, contact, remark, phone } = req.body;
    // items: [{ product_id, quantity }]
    let total_price = 0;
    for (const item of items) {
      const product = await Product.findByPk(item.product_id);
      if (!product) return res.status(400).json({ msg: `商品ID${item.product_id}不存在` });
      if (product.stock < item.quantity) return res.status(400).json({ msg: `商品${product.name}库存不足` });
      total_price += product.price * item.quantity;
    }
    const order = await Order.create({
      user_id: req.user.id,
      total_price,
      status: '进行中',
      address,
      contact,
      remark,
      phone
    });
    for (const item of items) {
      const product = await Product.findByPk(item.product_id);
      await OrderItem.create({
        order_id: order.id,
        product_id: item.product_id,
        quantity: item.quantity,
        price: product.price
      });
      // 扣减库存
      product.stock -= item.quantity;
      await product.save();
    }
    res.json({ msg: '下单成功', order_id: order.id });
  } catch (err) {
    res.status(500).json({ msg: '下单失败', err });
  }
};

// 查询订单列表（管理员查全部，普通用户查自己），支持分页和搜索
exports.list = async (req, res) => {
  try {
    const page = parseInt(req.query.page, 10) || 1;
    const pageSize = parseInt(req.query.pageSize, 10) || 10;
    const keyword = req.query.keyword || '';
    const status = req.query.status;
    let where = {};
    if (req.user.user_type !== 2 && req.user.role !== 'admin') {
      where.user_id = req.user.id;
    }
    if (status) {
      where.status = status;
    }
    if (keyword) {
      where = {
        ...where,
        // 可按订单号、联系人等模糊查
        [Order.sequelize.Op.or]: [
          { id: { [Order.sequelize.Op.like]: `%${keyword}%` } },
          { contact: { [Order.sequelize.Op.like]: `%${keyword}%` } }
        ]
      }
    }
    const { count, rows } = await Order.findAndCountAll({
      where,
      include: [
        { model: User, as: 'user', attributes: ['username'] }
      ],
      order: [['created_at', 'DESC']],
      offset: (page - 1) * pageSize,
      limit: pageSize
    });
    res.json({ total: count, list: rows });
  } catch (err) {
    res.status(500).json({ msg: '获取订单失败', err });
  }
};

// 查询订单详情（管理员可查全部，普通用户只能查自己的）
exports.detail = async (req, res) => {
  try {
    const { id } = req.params;
    const order = await Order.findByPk(id, {
      include: [
        { model: User, as: 'user', attributes: ['username'] }
      ]
    });
    if (!order) return res.status(404).json({ msg: '订单不存在' });
    if (!(req.user.user_type === 2 || req.user.role === 'admin') && order.user_id !== req.user.id) {
      return res.status(403).json({ msg: '无权查看该订单' });
    }
    const items = await OrderItem.findAll({
      where: { order_id: id },
      include: [{ model: Product, as: 'product' }]
    });
    res.json({ order, items });
  } catch (err) {
    res.status(500).json({ msg: '获取订单详情失败', err });
  }
};

// 修改订单状态（仅管理员）
exports.updateStatus = async (req, res) => {
  try {
    const { id } = req.params;
    const { status } = req.body;
    const order = await Order.findByPk(id);
    if (!order) return res.status(404).json({ msg: '订单不存在' });
    order.status = status;
    await order.save();
    res.json({ msg: '订单状态更新成功', order });
  } catch (err) {
    res.status(500).json({ msg: '订单状态更新失败', err });
  }
};

// 删除订单（仅管理员）
exports.remove = async (req, res) => {
  try {
    const { id } = req.params;
    const order = await Order.findByPk(id);
    if (!order) return res.status(404).json({ msg: '订单不存在' });
    // 先删除订单明细
    await OrderItem.destroy({ where: { order_id: id } });
    // 再删除订单
    await order.destroy();
    res.json({ msg: '订单删除成功' });
  } catch (err) {
    res.status(500).json({ msg: '订单删除失败', err });
  }
};
